const dataList = document.getElementById('data-list');

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    // 登录和注册模态框功能
    const loginModal = document.getElementById('loginModal');
    const registerModal = document.getElementById('registerModal');
    const loginLink = document.querySelector('.login-register .login');
    const registerLink = document.querySelector('.login-register .register');
    const closeModalButtons = document.querySelectorAll('.close-modal');
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');

    // 显示登录模态框
    loginLink.addEventListener('click', function (e) {
        e.preventDefault();
        loginModal.style.display = 'block';
    });

    // 显示注册模态框
    registerLink.addEventListener('click', function (e) {
        e.preventDefault();
        registerModal.style.display = 'block';
    });

    // 关闭模态框
    closeModalButtons.forEach(button => {
        button.addEventListener('click', function () {
            const modal = this.closest('.modal');
            modal.style.display = 'none';
        });
    });

    // 点击模态框外部关闭
    window.addEventListener('click', function (e) {
        if (e.target === loginModal) {
            loginModal.style.display = 'none';
        }
        if (e.target === registerModal) {
            registerModal.style.display = 'none';
        }
    });

    // 登录表单提交
    loginForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;
        const remember = document.querySelector('input[name="remember"]').checked;

        // 模拟登录验证
        if (username && password) {
            alert('登录成功！\n用户名：' + username + '\n记住我：' + remember);
            loginModal.style.display = 'none';
            loginForm.reset();
        } else {
            alert('请输入用户名和密码');
        }
    });

    // 注册表单提交
    registerForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('registerConfirmPassword').value;
        const email = document.getElementById('registerEmail').value;
        const agreeTerms = document.querySelector('input[name="agreeTerms"]').checked;

        // 表单验证
        if (!username || !password || !confirmPassword || !email) {
            alert('请填写所有必填字段');
            return;
        }

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }

        if (!agreeTerms) {
            alert('请阅读并同意用户协议和隐私政策');
            return;
        }

        // 模拟注册成功
        alert('注册成功！\n用户名：' + username + '\n邮箱：' + email);
        registerModal.style.display = 'none';
        registerForm.reset();
    });
    // 菜单功能初始化 - 扩展公共菜单功能，添加特定的页面跳转逻辑
    const menuItems = document.querySelectorAll('.menu-item');
    const submenuItems = document.querySelectorAll('.submenu-item');

    menuItems.forEach(item => {
        // 保存原始的点击事件处理函数
        const originalClickHandler = item.onclick;

        // 添加自定义点击事件处理函数
        item.addEventListener('click', function (e) {
            // 特殊菜单处理：首页和工作动态
            const menuType = this.getAttribute('data-menu');
            if (menuType === 'home') {
                window.location.href = '../home/index.html';
                return;
            } else if (menuType === 'status') {
                window.location.href = '../work-status/index.html';
                return;
            } else if (menuType === 'notices') {
                window.location.href = '../notice-announcement/index.html';
                return;
            } else if (menuType === 'services') {
                window.location.href = '../public-service/index.html';
                return;
            } else if (menuType === 'overview') {
                window.location.href = '../archival-collections/index.html';
                return;
            } else if (menuType === 'culture') {
                window.location.href = '../chronicle-culture/index.html';
                return;
            }
        });
    });

    // 二级菜单点击事件处理
    submenuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.stopPropagation();

            // 获取submenu类型
            const submenuType = this.getAttribute('data-submenu');

            // 根据submenu类型设置跳转URL
            let targetUrl = '';
            if (submenuType === 'status1') {
                targetUrl = '../work-status/index.html?type=exhibition';
            } else if (submenuType === 'statu2') {
                targetUrl = '../work-status/index.html?type=inquiry';
            } else if (submenuType === 'service4') {
                targetUrl = '../public-service/index.html?type=exhibition';
            } else if (submenuType === 'service5') {
                targetUrl = '../public-service/index.html?type=inquiry';
            } else if (submenuType === 'service1') {
                targetUrl = '../public-service/index.html?type=reservation';
            } else if (submenuType === 'service2') {
                targetUrl = '../public-service/index.html?type=message';
            } else if (submenuType === 'service3') {
                targetUrl = '../public-service/index.html?type=donation';
            } else if (submenuType === 'overview1') {
                targetUrl = '../archival-collections/index.html?type=inquiry';
            } else if (submenuType === 'overview2') {
                targetUrl = '../archival-collections/index.html?type=exhibition';
            } else if (submenuType === 'culture1') {
                targetUrl = '../chronicle-culture/index.html?type=exhibition';
            } else if (submenuType === 'culture2') {
                targetUrl = '../chronicle-culture/index.html?type=inquiry';
            } else if (submenuType === 'culture3') {
                targetUrl = '../chronicle-culture/index.html?type=culture';
            }

            // 跳转到对应页面
            if (targetUrl) {
                window.location.href = targetUrl;
            }
        });
    });

    // 为快捷入口添加点击效果
    const accessItems = document.querySelectorAll('.access-item');
    accessItems.forEach(item => {
        item.addEventListener('click', function () {
            alert('您点击了：' + this.querySelector('p').textContent);
        });
    });

    // 为平台链接添加点击效果
    const platformItems = document.querySelectorAll('.platform-item');
    platformItems.forEach(item => {
        item.addEventListener('click', function () {
            alert('您点击了：' + this.querySelector('img').alt);
        });
    });

    // 为编研成果添加点击效果
    const caseItems = document.querySelectorAll('.case-item');
    caseItems.forEach(item => {
        item.addEventListener('click', function () {
            alert('您点击了：' + this.querySelector('.case-title').textContent);
        });
    });

    // 为网上展厅添加点击效果
    const exhibitionItems1 = document.querySelectorAll('.exhibition-item');
    exhibitionItems1.forEach(item => {
        item.addEventListener('click', function () {
            alert('您点击了：' + this.querySelector('.exhibition-title').textContent);
        });
    });

    // 为业内动态、法规标准、通知公告等列表项添加点击效果
    const listItems = document.querySelectorAll('.dynamic-item, .regulations-item, .notices-item');
    listItems.forEach(item => {
        item.addEventListener('click', function () {
            alert('您点击了：' + this.querySelector('.title').textContent);
        });
    });

    // 为主题教育横幅添加点击效果
    const themeEducation = document.querySelector('.theme-education');
    if (themeEducation) {
        themeEducation.addEventListener('click', function () {
            alert('学习贯彻习近平新时代中国特色社会主义思想主题教育');
        });
    }

    // 为section-title-pre添加tab切换功能 - 单位概况、馆办动态、业内动态
    const tabItems = document.querySelectorAll('.section-title-pre');
    const tabContents = document.querySelectorAll('.tab-content');

    tabItems.forEach(item => {
        item.addEventListener('click', function () {
            // 移除所有tab的active类
            tabItems.forEach(tab => tab.classList.remove('active'));
            // 为当前点击的tab添加active类
            this.classList.add('active');

            // 显示more元素
            if (moreButton) {
                moreButton.style.visibility = 'visible';
            }

            // 根据tab切换内容
            const tabText = this.textContent;
            if (tabText === '单位概况') {
                // 显示单位概况内容，隐藏其他内容
                document.getElementById('overview-unit').style.display = 'block';
                document.getElementById('overview-content').style.display = 'none';
                document.getElementById('work-dynamic-content').style.display = 'none';
            } else if (tabText === '馆办动态') {
                // 显示馆办动态内容，隐藏其他内容
                document.getElementById('overview-unit').style.display = 'none';
                document.getElementById('overview-content').style.display = 'block';
                document.getElementById('work-dynamic-content').style.display = 'none';
            } else if (tabText === '业内动态') {
                // 显示业内动态内容，隐藏其他内容
                document.getElementById('overview-unit').style.display = 'none';
                document.getElementById('overview-content').style.display = 'none';
                document.getElementById('work-dynamic-content').style.display = 'block';
            }
        });
    });

    // 默认激活第一个tab（单位概况）
    if (tabItems.length > 0) {
        tabItems[0].classList.add('active');
        // 默认显示第一个tab的内容（单位概况）
        document.getElementById('overview-unit').style.display = 'block';
        document.getElementById('overview-content').style.display = 'none';
        document.getElementById('work-dynamic-content').style.display = 'none';
    }

    // 为业内动态列表项添加点击效果
    const dynamicItems = document.querySelectorAll('.dynamic-item');
    dynamicItems.forEach(item => {
        item.addEventListener('click', function () {
            alert('您点击了：' + this.querySelector('.title').textContent);
        });
    });

    // 单位概况'更多'按钮功能实现
    const unitIntro = document.querySelector('.unit-intro');
    const unitIntroContainer = document.getElementById('overview-unit');
    const moreButton = document.querySelector('.tab-container .more');
    const homeContentContainer = document.querySelector('.home-content-container');
    const homeContent = document.querySelector('.home-content');
    const tabItems1 = document.querySelectorAll('.section-title-pre');
    if (unitIntro && unitIntroContainer && moreButton && homeContentContainer && homeContent && tabItems1.length > 0) {




        // 点击'更多'按钮的处理函数
        moreButton.addEventListener('click', function (e) {
            e.stopPropagation(); // 阻止事件冒泡

            // 获取other-content-container元素
            const otherContentContainer = document.querySelector('.other-content-container');

            // 隐藏home-content-container
            homeContentContainer.style.display = 'none';

            // 清空并设置other-content-container样式
            otherContentContainer.innerHTML = '';
            otherContentContainer.style.width = '100%';
            otherContentContainer.style.padding = '20px';
            otherContentContainer.style.boxSizing = 'border-box';
            otherContentContainer.style.backgroundColor = '#fff';
            otherContentContainer.style.minHeight = '400px';

            // 添加返回按钮
            const backButton = document.createElement('button');
            backButton.textContent = '返回';
            backButton.style.marginBottom = '20px';
            backButton.style.padding = '8px 16px';
            backButton.style.backgroundColor = '#fc5531';
            backButton.style.color = '#fff';
            backButton.style.border = 'none';
            backButton.style.borderRadius = '4px';
            backButton.style.cursor = 'pointer';

            // 添加返回按钮的点击事件
            backButton.addEventListener('click', function () {
                // 显示home-content-container
                homeContentContainer.style.display = 'flex';
                // 清空并隐藏other-content-container
                otherContentContainer.innerHTML = '';
                otherContentContainer.style.display = 'none';
            });

            // 添加标题
            const title = document.createElement('h2');
            
            // 获取当前激活的tab
            const activeTab = document.querySelector('.section-title-pre.active');
            const tabText = activeTab ? activeTab.textContent.trim() : '单位概况';
            title.textContent = tabText;
            
            title.style.marginBottom = '20px';
            title.style.color = '#333';
            title.style.textAlign = 'center';

            // 如果是单位概况，显示单位概况内容
            if (tabText === '单位概况') {
                // 添加单位概况内容
                const contentDiv = document.createElement('div');
                contentDiv.innerHTML = unitIntro.innerHTML;
                contentDiv.style.fontSize = '16px';
                contentDiv.style.lineHeight = '1.8';
                contentDiv.style.color = '#333';

                // 将返回按钮、标题和内容添加到other-content-container中
                otherContentContainer.appendChild(backButton);
                otherContentContainer.appendChild(title);
                otherContentContainer.appendChild(contentDiv);
            } 
            // 如果是馆办动态或业内动态，显示列表和分页
            else if (tabText === '馆办动态' || tabText === '业内动态') {
                // 创建列表容器
                const listContainer = document.createElement('div');
                listContainer.className = 'list-content';
                listContainer.style.marginBottom = '20px';
                
                // 创建动态列表
                const dynamicList = document.createElement('ul');
                dynamicList.className = 'dynamic-list-1';
                
                // 创建分页控件
                const pagination = document.createElement('div');
                pagination.className = 'pagination';
                pagination.innerHTML = `
                    <button id="prev-page">&lt;</button>
                    <span id="page-info"></span>
                    <button id="next-page">&gt;</button>
                    <div class="custom-select pagination-select">
                        <select id="page-size">
                            <option value="5">5条</option>
                            <option value="10" selected>10条</option>
                            <option value="20">20条</option>
                            <option value="50">50条</option>
                        </select>
                        <div class="arrow"></div>
                    </div>
                    <input type="number" id="page-input" placeholder="跳转到...">
                `;
                
                // 将列表和分页控件添加到容器中
                listContainer.appendChild(dynamicList);
                otherContentContainer.appendChild(backButton);
                otherContentContainer.appendChild(title);
                otherContentContainer.appendChild(listContainer);
                otherContentContainer.appendChild(pagination);
                
                // 等待DOM更新后再初始化动态列表
                setTimeout(() => {
                    initDynamicList(tabText);
                }, 10);
            }

            // 确保other-content-container是显示的
            otherContentContainer.style.display = 'block';
        });
    }

    // 为编研成果和馆藏年鉴添加tab切换功能
    const researchTabItems2 = document.querySelectorAll('.research-cases .section-title-pre');
    researchTabItems2.forEach(item => {
        item.addEventListener('click', function () {
            // 移除所有tab的active类
            researchTabItems2.forEach(tab => tab.classList.remove('active'));
            // 为当前点击的tab添加active类
            this.classList.add('active');
            
            // 获取对应的more按钮并显示
            const moreButton = this.parentElement.querySelector('.more');
            if (moreButton) {
                moreButton.style.visibility = 'visible';
            }

            // 根据tab切换内容
            const tabText = this.textContent;
            if (tabText === '编研成果') {
                document.getElementById('research-content').style.display = 'flex';
                document.getElementById('cases-content').style.display = 'none';
            } else if (tabText === '馆藏年鉴') {
                document.getElementById('research-content').style.display = 'none';
                document.getElementById('cases-content').style.display = 'flex';
            }
        });
    });

    // 初始化所有section-title-pre的more按钮为显示
    const allMoreButtons = document.querySelectorAll('.more');
    allMoreButtons.forEach(button => {
        button.style.visibility = 'visible';
    });

    // 馆办动态相关变量
    let exhibitionData = []; // 馆办动态数据
    let exhibitionCurrentPage = 1; // 馆办动态当前页码
    let exhibitionPageSize = 10; // 馆办动态每页显示数量
    let exhibitionTotalPages = 1; // 馆办动态总页数

    // 业内动态相关变量
    let inquiryData = []; // 业内动态数据
    let inquiryCurrentPage = 1; // 业内动态当前页码
    let inquiryPageSize = 10; // 业内动态每页显示数量
    let inquiryTotalPages = 1; // 业内动态总页数

    // 当前显示的数据类型
    let currentDataType = '';

    // 生成馆办动态数据（200条）
    function generateExhibitionData() {
        const titles = [
            '朝阳区档案馆开展{year}年度档案业务培训',
            '朝阳区档案信息化建设项目顺利通过验收',
            '朝阳区档案馆举办"铭记历史 砥砺前行"主题展览',
            '朝阳区完成{year}年度文件材料归档工作检查',
            '朝阳区地方志编纂工作取得新进展',
            '朝阳区召开档案工作联席会议 统筹推进全区档案事业发展',
            '朝阳区档案馆新馆建设项目获区政府重点支持',
            '朝阳区"十四五"档案事业发展规划实施情况评估会召开',
            '朝阳区领导调研区档案馆工作 强调做好存史资政育人',
            '朝阳区召开区委常委会会议 研究部署档案工作'
        ];

        const data = [];
        const currentYear = new Date().getFullYear();

        for (let i = 0; i < 200; i++) {
            const titleTemplate = titles[i % titles.length];
            const year = currentYear - Math.floor(i / 100);
            const title = titleTemplate.replace('{year}', year);

            // 生成日期：从当前日期往前推，保证日期唯一
            const date = new Date();
            date.setDate(date.getDate() - i - Math.floor(Math.random() * 30));
            const yearStr = date.getFullYear();
            const monthStr = String(date.getMonth() + 1).padStart(2, '0');
            const dayStr = String(date.getDate()).padStart(2, '0');
            const dateStr = `${yearStr}-${monthStr}-${dayStr}`;

            data.push({
                id: i + 1,
                title: title,
                date: dateStr
            });
        }

        return data.sort((a, b) => new Date(b.date) - new Date(a.date));
    }

    // 生成业内动态数据（300条）
    function generateInquiryData() {
        const titles = [
            '国家档案局关于加强{year}年档案安全工作的通知',
            '北京市档案局举办全市档案系统先进经验交流会',
            '全国档案工作会议在京召开 部署{year}年重点任务',
            '《北京市档案条例》修订工作启动',
            '数字档案馆建设国家标准发布实施',
            '全国档案信息化建设现场推进会召开',
            '国家档案局公布第五批中国档案文献遗产名录',
            '北京市档案馆举办"红色档案 百年记忆"主题展览',
            '档案专业人员职称评审工作开始申报',
            '全国档案科技成果推广应用交流会召开'
        ];

        const data = [];
        const currentYear = new Date().getFullYear();

        for (let i = 0; i < 300; i++) {
            const titleTemplate = titles[i % titles.length];
            const year = currentYear - Math.floor(i / 100);
            const title = titleTemplate.replace('{year}', year);

            // 生成日期：从当前日期往前推，保证日期唯一
            const date = new Date();
            date.setDate(date.getDate() - i - Math.floor(Math.random() * 30));
            const yearStr = date.getFullYear();
            const monthStr = String(date.getMonth() + 1).padStart(2, '0');
            const dayStr = String(date.getDate()).padStart(2, '0');
            const dateStr = `${yearStr}-${monthStr}-${dayStr}`;

            data.push({
                id: i + 1,
                title: title,
                date: dateStr
            });
        }

        return data.sort((a, b) => new Date(b.date) - new Date(a.date));
    }

    // 渲染数据列表
    function renderList(data) {
        console.log(data,'data')
        const dynamicList = document.querySelector('.dynamic-list-1');

        if (!dynamicList) return;
        console.log(dynamicList,'dynamicList')
        dynamicList.innerHTML = '';

        data.forEach(item => {
            const li = document.createElement('li');
            li.className = 'dynamic-item';
            li.innerHTML = `
                <div class="title">${item.title}</div>
                <div class="date">${item.date}</div>
            `;

            // 添加点击事件
            li.addEventListener('click', function () {
                alert('您点击了：' + item.title);
            });

            dynamicList.appendChild(li);
        });
        console.log(dynamicList,'dynamicList')
    }

    // 渲染馆办动态分页信息
    function renderExhibitionPagination() {
        const pageInfo = document.querySelector('#page-info');
        if (!pageInfo) return;
        
        let pageNumbers = '';

        // 始终显示第一页
        if (exhibitionCurrentPage === 1) {
            pageNumbers += '<span class="current page-item">1</span>';
        } else {
            pageNumbers += '<span class="page-item" onclick="goToExhibitionPage(1)">1</span>';
        }

        // 如果当前页大于4，显示省略号
        if (exhibitionCurrentPage > 4) {
            pageNumbers += '<span class="slide">...</span>';
        }

        // 显示当前页前后各两页
        let start = Math.max(2, exhibitionCurrentPage - 2);
        let end = Math.min(exhibitionTotalPages - 1, exhibitionCurrentPage + 2);
        console.log(end,start,'33333')
        for (let i = start; i <= end; i++) {
            if (i === exhibitionCurrentPage) {
                pageNumbers += `<span class="current page-item">${i}</span>`;
            } else {
                pageNumbers += `<span class="page-item" onclick="goToExhibitionPage(${i})">${i}</span>`;
            }
        }

        // 如果当前页小于总页数-3，显示省略号
        if (exhibitionCurrentPage < exhibitionTotalPages - 3) {
            pageNumbers += '<span class="slide">...</span>';
        }

        // 始终显示最后一页
        if (exhibitionTotalPages > 1) {
            if (exhibitionCurrentPage === exhibitionTotalPages) {
                pageNumbers += `<span class="current page-item">${exhibitionTotalPages}</span>`;
            } else {
                pageNumbers += `<span class="page-item" onclick="goToExhibitionPage(${exhibitionTotalPages})">${exhibitionTotalPages}</span>`;
            }
        }

        pageInfo.innerHTML = pageNumbers;

        // 更新上一页、下一页按钮状态和样式
        const prevBtn = document.querySelector('#prev-page');
        const nextBtn = document.querySelector('#next-page');
        if (prevBtn && nextBtn) {
            prevBtn.disabled = exhibitionCurrentPage <= 1;
            nextBtn.disabled = exhibitionCurrentPage >= exhibitionTotalPages;

            // 为禁用状态的按钮添加样式
            if (prevBtn.disabled) {
                prevBtn.style.backgroundColor = '#f9f9f9';
                prevBtn.style.cursor = 'not-allowed';
            } else {
                prevBtn.style.backgroundColor = '';
                prevBtn.style.cursor = '';
            }

            if (nextBtn.disabled) {
                nextBtn.style.backgroundColor = '#f9f9f9';
                nextBtn.style.cursor = 'not-allowed';
            } else {
                nextBtn.style.backgroundColor = '';
                nextBtn.style.cursor = '';
            }
        }

        // 更新页码输入框
        const pageInput = document.querySelector('#page-input');
        if (pageInput) {
            pageInput.value = exhibitionCurrentPage;
        }
    }

    // 渲染业内动态分页信息
    function renderInquiryPagination() {
        const pageInfo = document.querySelector('#page-info');
        if (!pageInfo) return;
        
        let pageNumbers = '';

        // 始终显示第一页
        if (inquiryCurrentPage === 1) {
            pageNumbers += '<span class="current page-item">1</span>';
        } else {
            pageNumbers += '<span class="page-item" onclick="goToInquiryPage(1)">1</span>';
        }

        // 如果当前页大于4，显示省略号
        if (inquiryCurrentPage > 4) {
            pageNumbers += '<span class="slide">...</span>';
        }

        // 显示当前页前后各两页
        let start = Math.max(2, inquiryCurrentPage - 2);
        let end = Math.min(inquiryTotalPages - 1, inquiryCurrentPage + 2);

        for (let i = start; i <= end; i++) {
            if (i === inquiryCurrentPage) {
                pageNumbers += `<span class="current page-item">${i}</span>`;
            } else {
                pageNumbers += `<span class="page-item" onclick="goToInquiryPage(${i})">${i}</span>`;
            }
        }

        // 如果当前页小于总页数-3，显示省略号
        if (inquiryCurrentPage < inquiryTotalPages - 3) {
            pageNumbers += '<span class="slide">...</span>';
        }

        // 始终显示最后一页
        if (inquiryTotalPages > 1) {
            if (inquiryCurrentPage === inquiryTotalPages) {
                pageNumbers += `<span class="current page-item">${inquiryTotalPages}</span>`;
            } else {
                pageNumbers += `<span class="page-item" onclick="goToInquiryPage(${inquiryTotalPages})">${inquiryTotalPages}</span>`;
            }
        }

        pageInfo.innerHTML = pageNumbers;

        // 更新上一页、下一页按钮状态和样式
        const prevBtn = document.querySelector('#prev-page');
        const nextBtn = document.querySelector('#next-page');
        if (prevBtn && nextBtn) {
            prevBtn.disabled = inquiryCurrentPage <= 1;
            nextBtn.disabled = inquiryCurrentPage >= inquiryTotalPages;

            // 为禁用状态的按钮添加样式
            if (prevBtn.disabled) {
                prevBtn.style.backgroundColor = '#f9f9f9';
                prevBtn.style.cursor = 'not-allowed';
            } else {
                prevBtn.style.backgroundColor = '';
                prevBtn.style.cursor = '';
            }

            if (nextBtn.disabled) {
                nextBtn.style.backgroundColor = '#f9f9f9';
                nextBtn.style.cursor = 'not-allowed';
            } else {
                nextBtn.style.backgroundColor = '';
                nextBtn.style.cursor = '';
            }
        }

        // 更新页码输入框
        const pageInput = document.querySelector('#page-input');
        if (pageInput) {
            pageInput.value = inquiryCurrentPage;
        }
    }

    // 切换馆办动态页码
    function changeExhibitionPage(page) {
        console.log(exhibitionTotalPages,'exhibitionTotalPages')
        console.log(page,'page')

        if (page < 1 || page > exhibitionTotalPages) {
            return;
        }

        exhibitionCurrentPage = page;

        // 计算当前页显示的数据
        const startIndex = (exhibitionCurrentPage - 1) * exhibitionPageSize;
        const endIndex = Math.min(startIndex + exhibitionPageSize, exhibitionData.length);
        const pageData = exhibitionData.slice(startIndex, endIndex);

        // 重新渲染列表和分页
        renderList(pageData);
        renderExhibitionPagination();
    }

    // 切换业内动态页码
    function changeInquiryPage(page) {
        if (page < 1 || page > inquiryTotalPages) {
            return;
        }

        inquiryCurrentPage = page;

        // 计算当前页显示的数据
        const startIndex = (inquiryCurrentPage - 1) * inquiryPageSize;
        const endIndex = Math.min(startIndex + inquiryPageSize, inquiryData.length);
        const pageData = inquiryData.slice(startIndex, endIndex);

        // 重新渲染列表和分页
        renderList(pageData);
        renderInquiryPagination();
    }

    // 切换馆办动态每页显示数量
    function changeExhibitionPageSize(size) {
        exhibitionPageSize = parseInt(size);
        exhibitionCurrentPage = 1;

        // 重新计算总页数
        exhibitionTotalPages = Math.ceil(exhibitionData.length / exhibitionPageSize);

        // 重新渲染列表和分页
        changeExhibitionPage(1);
    }

    // 切换业内动态每页显示数量
    function changeInquiryPageSize(size) {
        inquiryPageSize = parseInt(size);
        inquiryCurrentPage = 1;

        // 重新计算总页数
        inquiryTotalPages = Math.ceil(inquiryData.length / inquiryPageSize);

        // 重新渲染列表和分页
        changeInquiryPage(1);
    }

    // 在全局作用域中定义馆办动态的goToPage函数
    window.goToExhibitionPage = function (page) {
        if (page >= 1 && page <= exhibitionTotalPages) {
            exhibitionCurrentPage = page;

            // 计算当前页显示的数据
            const startIndex = (exhibitionCurrentPage - 1) * exhibitionPageSize;
            const endIndex = Math.min(startIndex + exhibitionPageSize, exhibitionData.length);
            const pageData = exhibitionData.slice(startIndex, endIndex);

            // 重新渲染列表和分页
            renderList(pageData);
            renderExhibitionPagination();
        }
    };

    // 在全局作用域中定义业内动态的goToPage函数
    window.goToInquiryPage = function (page) {
        if (page >= 1 && page <= inquiryTotalPages) {
            inquiryCurrentPage = page;

            // 计算当前页显示的数据
            const startIndex = (inquiryCurrentPage - 1) * inquiryPageSize;
            const endIndex = Math.min(startIndex + inquiryPageSize, inquiryData.length);
            const pageData = inquiryData.slice(startIndex, endIndex);

            // 重新渲染列表和分页
            renderList(pageData);
            renderInquiryPagination();
        }
    };

    // 初始化动态列表
    function initDynamicList(tabType) {
        // 初始化数据
        exhibitionData = generateExhibitionData();
        inquiryData = generateInquiryData();
        
        // 设置当前数据类型
        currentDataType = tabType;
        
        // 分页控件事件处理
        const prevBtn = document.querySelector('#prev-page');
        const nextBtn = document.querySelector('#next-page');
        const pageSizeSelect = document.querySelector('#page-size');
        const pageInput = document.querySelector('#page-input');
        
        // 清空之前的事件监听
        const newPrevBtn = prevBtn.cloneNode(true);
        prevBtn.parentNode.replaceChild(newPrevBtn, prevBtn);
        
        const newNextBtn = nextBtn.cloneNode(true);
        nextBtn.parentNode.replaceChild(newNextBtn, nextBtn);
        
        // 根据不同的数据类型设置不同的分页逻辑
        if (tabType === '馆办动态') {
            // 初始化馆办动态页码和总页数
            exhibitionCurrentPage = 1;
            console.log(exhibitionData.length,'exhibitionData.length')
            console.log(exhibitionPageSize,'exhibitionData.length')

            exhibitionTotalPages = Math.ceil(exhibitionData.length / exhibitionPageSize);
            
            // 初始渲染
            const startIndex = (exhibitionCurrentPage - 1) * exhibitionPageSize;
            const endIndex = Math.min(startIndex + exhibitionPageSize, exhibitionData.length);
            const pageData = exhibitionData.slice(startIndex, endIndex);
            renderList(pageData);
            renderExhibitionPagination();
            
            // 绑定馆办动态的事件处理
            newPrevBtn.addEventListener('click', function () {
                changeExhibitionPage(exhibitionCurrentPage - 1);
            });
            
            newNextBtn.addEventListener('click', function () {
                changeExhibitionPage(exhibitionCurrentPage + 1);
            });
            
            if (pageSizeSelect) {
                pageSizeSelect.value = exhibitionPageSize;
                pageSizeSelect.addEventListener('change', function () {
                    changeExhibitionPageSize(this.value);
                });
            }
            
            if (pageInput) {
                pageInput.value = exhibitionCurrentPage;
                // 为页码输入框添加回车和失焦事件
                pageInput.addEventListener('keypress', function (e) {
                    if (e.key === 'Enter') {
                        const page = parseInt(this.value);
                        if (!isNaN(page)) {
                            changeExhibitionPage(page);
                        } else {
                            this.value = exhibitionCurrentPage;
                        }
                    }
                });

                // 添加鼠标离开时触发页面翻页
                pageInput.addEventListener('blur', function () {
                    const page = parseInt(this.value);
                    if (!isNaN(page)) {
                        changeExhibitionPage(page);
                    } else {
                        this.value = exhibitionCurrentPage;
                    }
                });
            }
        } else if (tabType === '业内动态') {
            // 初始化业内动态页码和总页数
            inquiryCurrentPage = 1;
            inquiryTotalPages = Math.ceil(inquiryData.length / inquiryPageSize);
            
            // 初始渲染
            const startIndex = (inquiryCurrentPage - 1) * inquiryPageSize;
            const endIndex = Math.min(startIndex + inquiryPageSize, inquiryData.length);
            const pageData = inquiryData.slice(startIndex, endIndex);
            renderList(pageData);
            renderInquiryPagination();
            // 绑定业内动态的事件处理
            newPrevBtn.addEventListener('click', function () {
                changeInquiryPage(inquiryCurrentPage - 1);
            });
            
            newNextBtn.addEventListener('click', function () {
                changeInquiryPage(inquiryCurrentPage + 1);
            });
            
            if (pageSizeSelect) {
                pageSizeSelect.value = inquiryPageSize;
                pageSizeSelect.addEventListener('change', function () {
                    changeInquiryPageSize(this.value);
                });
            }
            
            if (pageInput) {
                pageInput.value = inquiryCurrentPage;
                // 为页码输入框添加回车和失焦事件
                pageInput.addEventListener('keypress', function (e) {
                    if (e.key === 'Enter') {
                        const page = parseInt(this.value);
                        if (!isNaN(page)) {
                            changeInquiryPage(page);
                        } else {
                            this.value = inquiryCurrentPage;
                        }
                    }
                });

                // 添加鼠标离开时触发页面翻页
                pageInput.addEventListener('blur', function () {
                    const page = parseInt(this.value);
                    if (!isNaN(page)) {
                        changeInquiryPage(page);
                    } else {
                        this.value = inquiryCurrentPage;
                    }
                });
            }
        }
    }

    // Overview Image轮播图功能
    let overviewSlideIndex = 0;
    const overviewSlides = document.querySelectorAll('.overview-slide');
    const overviewContainer = document.querySelector('.overview-carousel-container');
    const overviewIndicatorsContainer = document.querySelector('.overview-indicators');

    // 设置轮播图容器样式
    if (overviewContainer) {
        overviewContainer.style.position = 'relative';
        overviewContainer.style.height = '100%';
        overviewContainer.style.width = '100%';
        overviewContainer.style.overflow = 'hidden';
    }

    // 设置轮播图图片样式
    overviewSlides.forEach((slide, index) => {
        slide.style.position = 'absolute';
        slide.style.top = '0';
        slide.style.left = '0';
        slide.style.width = '100%';
        slide.style.height = '100%';
        slide.style.objectFit = 'cover';
        slide.style.display = index === 0 ? 'block' : 'none';
    });

    // 设置指示器容器样式
    if (overviewIndicatorsContainer) {
        overviewIndicatorsContainer.style.position = 'absolute';
        overviewIndicatorsContainer.style.bottom = '10px';
        overviewIndicatorsContainer.style.right = '10px';
        overviewIndicatorsContainer.style.display = 'flex';
        overviewIndicatorsContainer.style.gap = '6px';
        overviewIndicatorsContainer.style.zIndex = '10';
    }

    // 动态创建指示器
    function createOverviewIndicators() {
        if (!overviewIndicatorsContainer) return;

        overviewIndicatorsContainer.innerHTML = '';

        overviewSlides.forEach((_, index) => {
            const indicator = document.createElement('div');
            // 设置指示器样式（灰色圆圈，6px）
            indicator.style.width = '6px';
            indicator.style.height = '6px';
            indicator.style.borderRadius = '50%';
            indicator.style.backgroundColor = index === 0 ? '#fc5531' : 'gray';
            indicator.style.cursor = 'pointer';
            indicator.dataset.index = index;

            // 添加点击事件
            indicator.addEventListener('click', function () {
                // 停止当前计时器
                clearInterval(overviewSlideInterval);

                // 隐藏当前显示的图片
                overviewSlides[overviewSlideIndex].style.display = 'none';

                // 更新索引
                overviewSlideIndex = parseInt(this.dataset.index);

                // 显示选中的图片
                overviewSlides[overviewSlideIndex].style.display = 'block';

                // 更新指示器高亮状态
                updateOverviewIndicators();

                // 重新启动计时器
                overviewSlideInterval = setInterval(overviewNextSlide, 3000);
            });

            overviewIndicatorsContainer.appendChild(indicator);
        });
    }

    // 更新指示器高亮状态
    function updateOverviewIndicators() {
        const indicators = overviewIndicatorsContainer.querySelectorAll('div');
        indicators.forEach((indicator, index) => {
            indicator.style.backgroundColor = index === overviewSlideIndex ? '#fc5531' : 'gray';
        });
    }

    // 轮播图自动切换函数
    function overviewNextSlide() {
        // 隐藏当前显示的图片
        overviewSlides[overviewSlideIndex].style.display = 'none';

        // 更新索引
        overviewSlideIndex = (overviewSlideIndex + 1) % overviewSlides.length;

        // 显示下一张图片
        overviewSlides[overviewSlideIndex].style.display = 'block';

        // 更新指示器高亮状态
        updateOverviewIndicators();
    }

    // 创建指示器
    createOverviewIndicators();

    // 设置自动轮播，每3秒切换一次
    let overviewSlideInterval = setInterval(overviewNextSlide, 3000);

    // 默认激活编研成果tab
    if (researchTabItems2.length > 0) {
        researchTabItems2[0].classList.add('active');
    }

    // 为网上展厅和主题活动添加tab切换功能
    const exhibitionTabItems = document.querySelectorAll('.online-exhibition .section-title-pre');
    exhibitionTabItems.forEach(item => {
        item.addEventListener('click', function () {
            // 移除所有tab的active类
            exhibitionTabItems.forEach(tab => tab.classList.remove('active'));
            // 为当前点击的tab添加active类
            this.classList.add('active');

            // 根据tab切换内容
            const tabText = this.textContent;
            if (tabText === '特色展览') {
                document.getElementById('exhibition-content').style.display = 'block';
                document.getElementById('activities-content').style.display = 'none';
            } else if (tabText === '主题活动') {
                document.getElementById('exhibition-content').style.display = 'none';
                document.getElementById('activities-content').style.display = 'block';
            }
        });
    });

    // 默认激活特色展览tab
    if (exhibitionTabItems.length > 0) {
        exhibitionTabItems[0].classList.add('active');
    }

    // 为编研成果和网上展厅的项目添加点击效果
    const caseItems2 = document.querySelectorAll('.case-item');
    caseItems2.forEach(item => {
        item.addEventListener('click', function () {
            // 这里可以添加点击后的跳转逻辑
            console.log('Case item clicked:', this.querySelector('.case-title').textContent);
        });
    });

    const exhibitionItems2 = document.querySelectorAll('.exhibition-item');
    exhibitionItems2.forEach(item => {
        item.addEventListener('click', function () {
            // 这里可以添加点击后的跳转逻辑
            console.log('Exhibition item clicked:', this.querySelector('.exhibition-title').textContent);
        });
    });

    // 编研成果轮播图功能
    let researchSlideIndex = 0;
    const researchContainer = document.querySelector('#research-content .cases-container');
    const researchItems = document.querySelectorAll('#research-content .case-item');
    const researchLeftArrow = document.querySelector('.research-left-arrow');
    const researchRightArrow = document.querySelector('.research-right-arrow');
    const researchTotalItems = researchItems.length;
    const researchItemsPerView = 5;
    const researchMaxIndex = Math.max(0, researchTotalItems - researchItemsPerView);

    // 计算每个item的宽度（考虑到间距）
    function calculateItemWidth(items, perView, gap) {
        if (items.length === 0) return 0;
        // 移除之前设置的宽度，以便获取实际的容器宽度
        items.forEach(item => {
            item.style.width = 'auto';
        });

        const containerWidth = items[0].parentElement.clientWidth;
        return (containerWidth - (gap * (perView - 1))) / perView;
    }

    function updateResearchSlide() {
        // 每个item之间的间距为20px
        const itemWidth = calculateItemWidth(researchItems, researchItemsPerView, 20);

        // 设置每个item的固定宽度
        researchItems.forEach(item => {
            item.style.width = `${itemWidth}px`;
        });

        // 计算位移量，考虑到间距
        const translateX = -researchSlideIndex * (itemWidth + 20);
        researchContainer.style.transform = `translateX(${translateX}px)`;
    }

    researchLeftArrow.addEventListener('click', function () {
        researchSlideIndex = Math.max(0, researchSlideIndex - 1);
        updateResearchSlide();
    });

    researchRightArrow.addEventListener('click', function () {
        researchSlideIndex = Math.min(researchMaxIndex, researchSlideIndex + 1);
        updateResearchSlide();
    });

    // 馆藏年鉴轮播图功能
    let casesSlideIndex = 0;
    const casesContainer = document.querySelector('#cases-content .cases-container');
    const casesItems = document.querySelectorAll('#cases-content .case-item');
    const casesLeftArrow = document.querySelector('.cases-left-arrow');
    const casesRightArrow = document.querySelector('.cases-right-arrow');
    const casesTotalItems = casesItems.length;
    const casesItemsPerView = 5;
    const casesMaxIndex = Math.max(0, casesTotalItems - casesItemsPerView);

    function updateCasesSlide() {
        // 每个item之间的间距为20px
        const itemWidth = calculateItemWidth(casesItems, casesItemsPerView, 20);

        // 设置每个item的固定宽度
        casesItems.forEach(item => {
            item.style.width = `${itemWidth}px`;
        });

        // 计算位移量，考虑到间距
        const translateX = -casesSlideIndex * (itemWidth + 20);
        casesContainer.style.transform = `translateX(${translateX}px)`;
    }

    casesLeftArrow.addEventListener('click', function () {
        casesSlideIndex = Math.max(0, casesSlideIndex - 1);
        updateCasesSlide();
    });

    casesRightArrow.addEventListener('click', function () {
        casesSlideIndex = Math.min(casesMaxIndex, casesSlideIndex + 1);
        updateCasesSlide();
    });

    // 在窗口大小改变时重新计算轮播图
    window.addEventListener('resize', function () {
        updateResearchSlide();
        updateCasesSlide();
        updateExhibitionSlide();
    });

    // 初始化轮播图
    updateResearchSlide();
    updateCasesSlide();

    // 网上展厅轮播图功能
    let exhibitionSlideIndex = 0;
    const exhibitionContainer = document.querySelector('#exhibition-content .exhibition-container');
    const exhibitionItems = document.querySelectorAll('#exhibition-content .exhibition-item');
    const exhibitionItemsPerView = 3;

    // 为网上展厅添加轮播图箭头
    const exhibitionParent = document.querySelector('.online-exhibition');
    const exhibitionArrowsHTML = `
        <div class="carousel-arrows">
            <div class="arrow left-arrow exhibition-left-arrow">&lt;</div>
            <div class="arrow right-arrow exhibition-right-arrow">&gt;</div>
        </div>
    `;
    exhibitionParent.insertAdjacentHTML('beforeend', exhibitionArrowsHTML);

    const exhibitionLeftArrow = document.querySelector('.exhibition-left-arrow');
    const exhibitionRightArrow = document.querySelector('.exhibition-right-arrow');
    const exhibitionTotalItems = exhibitionItems.length;
    const exhibitionMaxIndex = Math.max(0, exhibitionTotalItems - exhibitionItemsPerView);
    updateExhibitionSlide();


    function updateExhibitionSlide() {
        // 获取一个exhibition-item的实际宽度
        const firstItem = exhibitionItems[0];
        if (!firstItem) return;

        const itemWidth = firstItem.offsetWidth;

        // 计算位移量，考虑到间距
        const translateX = -exhibitionSlideIndex * (itemWidth + 20); // 20px是gap
        exhibitionContainer.style.transform = `translateX(${translateX}px)`;
    }

    exhibitionLeftArrow.addEventListener('click', function () {
        exhibitionSlideIndex = Math.max(0, exhibitionSlideIndex - 1);
        updateExhibitionSlide();

        // 重置自动轮播计时器
        clearInterval(exhibitionSlideInterval);
        exhibitionSlideInterval = setInterval(exhibitionNextSlide, 3000);
    });

    exhibitionRightArrow.addEventListener('click', function () {
        exhibitionSlideIndex = Math.min(exhibitionMaxIndex, exhibitionSlideIndex + 1);
        updateExhibitionSlide();

        // 重置自动轮播计时器
        clearInterval(exhibitionSlideInterval);
        exhibitionSlideInterval = setInterval(exhibitionNextSlide, 3000);
    });

    function exhibitionNextSlide() {
        exhibitionSlideIndex = (exhibitionSlideIndex + 1) % (exhibitionMaxIndex + 1);
        updateExhibitionSlide();
    }

    // 为网上展厅添加自动轮播
    let exhibitionSlideInterval = setInterval(exhibitionNextSlide, 3000);

    // 为编研成果添加自动轮播
    function researchNextSlide() {
        researchSlideIndex = (researchSlideIndex + 1) % (researchMaxIndex + 1);
        updateResearchSlide();
    }

    let researchSlideInterval = setInterval(researchNextSlide, 3000);

    // 为馆藏年鉴添加自动轮播
    function casesNextSlide() {
        casesSlideIndex = (casesSlideIndex + 1) % (casesMaxIndex + 1);
        updateCasesSlide();
    }

    let casesSlideInterval = setInterval(casesNextSlide, 3000);

    // 为编研成果和馆藏年鉴的箭头添加点击事件，重置自动轮播计时器
    researchLeftArrow.addEventListener('click', function () {
        clearInterval(researchSlideInterval);
        researchSlideInterval = setInterval(researchNextSlide, 3000);
    });

    researchRightArrow.addEventListener('click', function () {
        clearInterval(researchSlideInterval);
        researchSlideInterval = setInterval(researchNextSlide, 3000);
    });

    casesLeftArrow.addEventListener('click', function () {
        clearInterval(casesSlideInterval);
        casesSlideInterval = setInterval(casesNextSlide, 3000);
    });

    casesRightArrow.addEventListener('click', function () {
        clearInterval(casesSlideInterval);
        casesSlideInterval = setInterval(casesNextSlide, 3000);
    });

    // 在窗口大小改变时重新计算轮播图
    window.addEventListener('resize', function () {
        updateResearchSlide();
        updateCasesSlide();
        updateExhibitionSlide();
    });

    // 初始化网上展厅轮播图
    updateExhibitionSlide();

    // 在tab切换时重置轮播图索引
    const researchTabItems = document.querySelectorAll('.research-cases .section-title-pre');
    researchTabItems.forEach(item => {
        item.addEventListener('click', function () {
            if (this.textContent.trim() === '编研成果') {
                researchSlideIndex = 0;
                updateResearchSlide();

                // 重置自动轮播计时器
                clearInterval(researchSlideInterval);
                researchSlideInterval = setInterval(researchNextSlide, 3000);
            } else if (this.textContent.trim() === '馆藏年鉴') {
                casesSlideIndex = 0;
                updateCasesSlide();

                // 重置自动轮播计时器
                clearInterval(casesSlideInterval);
                casesSlideInterval = setInterval(casesNextSlide, 3000);
            }
        });
    });

    // 在网上展厅tab切换时重置轮播图索引
    exhibitionTabItems.forEach(item => {
        item.addEventListener('click', function () {
            if (this.textContent.trim() === '特色展览') {
                exhibitionSlideIndex = 0;
                updateExhibitionSlide();

                // 重置自动轮播计时器
                clearInterval(exhibitionSlideInterval);
                exhibitionSlideInterval = setInterval(exhibitionNextSlide, 3000);
            }
        });
    });
});